﻿using System;
using System.IO;
using System.Threading.Tasks;
namespace ORS.OrderRobot
{
	public static class FileHelper
	{
		/// <summary>
		/// 保存文件到应用根目录下的指定相对路径
		/// </summary>
		/// <param name="relativePath">相对路径，如"files/test.txt"</param>
		/// <param name="content">文件内容</param>
		public static void SaveFile(string relativePath, byte[] content)
		{
			var root = AppContext.BaseDirectory;
			var fullPath = Path.Combine(root, relativePath);
			var dir = Path.GetDirectoryName(fullPath);
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			File.WriteAllBytes(fullPath, content);
		}

		/// <summary>
		/// 保存文本文件到应用根目录下的指定相对路径
		/// </summary>
		/// <param name="relativePath">相对路径，如"files/test.txt"</param>
		/// <param name="content">文本内容</param>
		/// <param name="encoding">文本编码，默认UTF8</param>
		public static void SaveTextFile(string relativePath, string content, System.Text.Encoding encoding = null)
		{
			var root = AppContext.BaseDirectory;
			var fullPath = Path.Combine(root, relativePath);
			var dir = Path.GetDirectoryName(fullPath);
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			if (encoding == null) encoding = System.Text.Encoding.UTF8;
			File.WriteAllText(fullPath, content, encoding);
		}

		/// <summary>
		/// 异步保存文件到应用根目录下的指定相对路径
		/// </summary>
		public static async Task SaveFileAsync(string relativePath, byte[] content)
		{
			var root = AppContext.BaseDirectory;
			var fullPath = Path.Combine(root, relativePath);
			var dir = Path.GetDirectoryName(fullPath);
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			await File.WriteAllBytesAsync(fullPath, content);
		}

		/// <summary>
		/// 异步保存文本文件到应用根目录下的指定相对路径
		/// </summary>
		public static async Task SaveTextFileAsync(string relativePath, string content, System.Text.Encoding encoding = null)
		{
			var root = AppContext.BaseDirectory;
			var fullPath = Path.Combine(root, relativePath);
			var dir = Path.GetDirectoryName(fullPath);
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			if (encoding == null) encoding = System.Text.Encoding.UTF8;
			await File.WriteAllTextAsync(fullPath, content, encoding);
		}
	}
}

